package com.lib.image.preview

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lib.image.LiveBusEvent
import com.lib.image.R
import com.lib.image.until.HeterotypicScreenUtils
import com.zhihu.matisse.ui.MatisseActivity

class PhotoEditorActivity : AppCompatActivity() {

    private lateinit var mViewModel: PhotoEditorViewModel

    companion object {

        private const val KEY_IMAGE_PATH = "key_image_path"

        @JvmStatic
        fun newIntent(activity: Activity, imagePath: String): Intent {
            val intent = Intent(activity, PhotoEditorActivity::class.java)
            intent.putExtra(KEY_IMAGE_PATH, imagePath)
            return intent
        }
    }

    override fun onSupportNavigateUp(): Boolean {
        return Navigation.findNavController(this, R.id.nav_photo_editor).navigateUp()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        HeterotypicScreenUtils.openFullScreenModel(this)
        setContentView(R.layout.activity_photo_editor)
        mViewModel = ViewModelProvider(this).get(PhotoEditorViewModel::class.java)
        mViewModel.getImagePath().value = intent.getStringExtra(KEY_IMAGE_PATH)
        bindListener()
    }

    private fun bindListener() {
        LiveEventBus.get(LiveBusEvent.EVENT_OPERATED, String::class.java).observe(this, {
            val intent = Intent()
            val list = arrayListOf<String>()
            list.add(it)
            intent.putStringArrayListExtra(MatisseActivity.EXTRA_RESULT_SELECTION_PATH, list)
            setResult(Activity.RESULT_OK, intent)
            finish()
        })
    }
}